﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebService.VO;

namespace WebService.DAO
{
    public class UserRatingDAO
    {
        private dbConnection conn;
        /// <summary>
        /// khởi tạo đối tượng xử lý dl
        /// </summary>
        public UserRatingDAO()
        {
            conn = new dbConnection();
        }
        /// <summary>
        /// Get user rating
        /// </summary>
        /// <param name="userRating"></param>
        /// <returns></returns>
        public int getUserRating(UserRatingVO userRating)
        {
            string query = "SELECT rating FROM tbl_UserRating WHERE ItemID = @ItemID AND DeviceID = @DeviceID";

            IDictionary<string, string> d = new Dictionary<string, string>();
            d.Add("@ItemID", userRating.Item.ItemId.ToString());
            d.Add("@DeviceID", userRating.Device.Id.ToString());

            return Convert.ToInt32(conn.ExecuteScalar(query, d, false));
        }
        /// <summary>
        /// Insert user rating
        /// </summary>
        /// <param name="userRating"></param>
        public void insertRating(UserRatingVO userRating)
        {
            string sqlInsert = "INSERT INTO tbl_UserRating VALUES(@ItemId, @DeviceId, @Rating)";

            IDictionary<string, string> d = new Dictionary<string, string>();

            d.Add("@ItemId", userRating.Item.ItemId.ToString());
            d.Add("@DeviceId", userRating.Device.Id.ToString());
            d.Add("@Rating", userRating.Rating.ToString());

            conn.ExecuteQuery(sqlInsert, d, false);
        }
        /// <summary>
        /// update user rating
        /// </summary>
        /// <param name="userRating"></param>
        public void updateRating(UserRatingVO userRating)
        {
            string sqlInsert = "update tbl_UserRating"
               + " set Rating=@Rating"
             + " WHERE ItemId=@ItemId and DeviceID=@DeviceId";

            IDictionary<string, string> d = new Dictionary<string, string>();
            d.Add("@ItemId", userRating.Item.ItemId.ToString());
            d.Add("@DeviceId", userRating.Device.Id.ToString());
            d.Add("@Rating", userRating.Rating.ToString());

            conn.ExecuteQuery(sqlInsert, d, false);
        }

        public bool checkUserRatingExist(UserRatingVO user)
        {
            string query = "SELECT count(*) FROM tbl_UserRating WHERE ItemID = @ItemID AND DeviceID = @DeviceID";

            IDictionary<string, string> d = new Dictionary<string, string>();
            d.Add("@ItemID", user.Item.ItemId.ToString());
            d.Add("@DeviceID", user.Device.Id.ToString());

            int kq = conn.ExecuteScalar(query, d, false);
            if (kq > 0)
                return true;
            return false;
        }
    }
}